﻿package com.alstudio.module.sns.weiboshare;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.alstudio.module.sns.base.SnsConfig;
import com.alstudio.module.sns.sina.SinaWeibo;
import com.alstudio.module.sns.sina.SinaWeibo.OnAuthEventListener;
import com.alstudio.pojo.module.user.User;
import com.alstudio.utils.formater.numeric.ALNumericUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.view.toast.MyToastUtil;
import com.loovee.imaohu.R;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;

public class SinaShare implements IWeiboShare {
	private static final String TAG = "ISinaShare";

	private boolean mForceLogin = true;

	private SinaWeibo mSinaWeibo;
	private Activity mActivity;
	private Callback mCallback;
	private String mContent;
	private String mImageFile;
	private boolean misAddLoovee;
	private boolean mIsShare;

	private boolean mShareFlag;
	private boolean mGetFriendsFlag;

	private boolean mShareWithImageUrl = false;
	private String mImageUrl;

	public SinaShare() {
		// mSinaWeibo = ThirdPartFactory.getSinaWeiboInstance(App.ctx);
	}

	public SinaWeibo getSinaWeibo() {
		return mSinaWeibo;
	}

	@Override
	public void authorize(Activity activity, Callback callback) {
		if (!mSinaWeibo.isSessionValid()) {
			mShareFlag = false;
			mGetFriendsFlag = false;
			mActivity = activity;
			mCallback = callback;
			mSinaWeibo = ThirdPartFactory.getSinaWeiboInstance(activity);
			mSinaWeibo.authorize(activity, mSinaAuthListener);
			return;
		}

		if (callback != null) {
			callback.onSuccess(IWeiboShare.ACTION_AUTHORIZE);
		}
	}

	@Override
	public void share(Activity activity, String content, String imageFile,
			boolean isAddLoovee, Callback callback) {

		if (!TextUtils.isEmpty(imageFile)) {

			mActivity = activity;
			mContent = content;
			mImageFile = imageFile;
			misAddLoovee = isAddLoovee;
			mIsShare = true;
			mCallback = callback;
			mShareWithImageUrl = false;
			mSinaWeibo = ThirdPartFactory.getSinaWeiboInstance(activity);

			if (!mSinaWeibo.isSessionValid()) {
				mShareFlag = true;
				mSinaWeibo.authorize(mActivity, mSinaAuthListener);
				return;
			}

			try {
				mActivity.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						MyToastUtil
								.getInstance()
								.showToastOnCenter(
										mActivity
												.getString(R.string.TxtStartSharing));
						if (mCallback != null) {
							mCallback.onStartShare();
						}
					}
				});
				mSinaWeibo.updateStatusWithImage(content, imageFile, listener);
			} catch (WeiboException e) {
				e.printStackTrace();
				// if (e.getStatusCode() != 20017 && e.getStatusCode() != 20019)
				// {
				// if (mCallback != null)
				// mCallback.onFailed(IWeiboShare.ACTION_SHARE);
				// }
			}

			// if (mCallback != null)
			// mCallback.onSuccess(IWeiboShare.ACTION_SHARE);
		} else {
			MyToastUtil.getInstance().showCenterToastOnCenter("图片地址为空!");
		}
	}

	@Override
	public void shareWithImageUrl(Activity activity, String content,
			String imageUrl, boolean isAddLoovee, Callback callback) {
		mSinaWeibo = ThirdPartFactory.getSinaWeiboInstance(activity);
		mActivity = activity;
		mCallback = callback;
		mContent = content;
		misAddLoovee = isAddLoovee;
		mIsShare = true;
		mShareWithImageUrl = true;
		mImageUrl = imageUrl;

		if (!mSinaWeibo.isSessionValid()) {
			mShareFlag = true;
			mSinaWeibo.authorize(mActivity, mSinaAuthListener);
			return;
		}
		if (!TextUtils.isEmpty(mImageUrl)) {
			imageUrl = mImageUrl;
		} else {
			imageUrl = WeiboShareUtil.getDefaultLooveeAppLogoUrl();
		}

		if (misAddLoovee) {
			try {
				mSinaWeibo.createFriendship(
						ALNumericUtils.parseLong(SnsConfig.SINA_LOOVEE_OFFICAL_UID, 0),
						new RequestListener() {

							@Override
							public void onIOException(IOException arg0) {
								// TODO Auto-generated method stub
								arg0.printStackTrace();
								if (mCallback != null)
									mCallback
											.onFailed(IWeiboShare.ACTION_FOLLOW);
							}

							@Override
							public void onError(WeiboException arg0) {
								// TODO Auto-generated method stub
								arg0.printStackTrace();
								// 20506：已关注，忽略此错误
//								if (arg0.getStatusCode() != 20506) {
//									if (mCallback != null)
//										mCallback
//												.onFailed(IWeiboShare.ACTION_FOLLOW);
//								}

								if (mCallback != null)
									mCallback
											.onFailed(IWeiboShare.ACTION_FOLLOW);
								
							}

							@Override
							public void onComplete(String arg0) {
								// TODO Auto-generated method stub
								ALLog.e("成功了  " + arg0);
								if (mCallback != null)
									mCallback
											.onSuccess(IWeiboShare.ACTION_FOLLOW);
							}

							@Override
							public void onComplete4binary(
									ByteArrayOutputStream arg0) {
								// TODO Auto-generated method stub
								
							}
						});
				misAddLoovee = false;
			} catch (WeiboException e) {
				e.printStackTrace();

				// 20506：已关注，忽略此错误
				// if (e.getStatusCode() != 20506) {
				// if (mCallback != null)
				// mCallback.onFailed(IWeiboShare.ACTION_FOLLOW);
				// }
			}

			// if (mCallback != null)
			// mCallback.onSuccess(IWeiboShare.ACTION_FOLLOW);
		}

		try {
			mActivity.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					MyToastUtil.getInstance().showToastOnCenter(
							mActivity.getString(R.string.TxtStartSharing));
					if (mCallback != null) {
						mCallback.onStartShare();
					}
				}
			});
//			imageUrl = "http://www.imeach.com/attachments/softpic/_138268612028788.jpg";
//			imageUrl = "http://116.254.203.73/attachments/ad/20130305.jpg";
			mSinaWeibo.updateStatusWithImageUrl(content, imageUrl, listener);
		} catch (WeiboException e) {

			e.printStackTrace();

			// 20017：提交相似的信息，忽略此错误
			// 20019：提交相同的信息，忽略此错误
			// if (e.getStatusCode() != 20017 && e.getStatusCode() != 20019) {
			// if (mCallback != null)
			// mCallback.onFailed(IWeiboShare.ACTION_SHARE);
			// }
		}

		// if (mCallback != null)
		// mCallback.onSuccess(IWeiboShare.ACTION_SHARE);

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (mSinaWeibo != null) {
			mSinaWeibo.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	private void doShare() {
		// if (!mSinaWeibo.isSessionValid()) {
		// mShareFlag = true;
		// // mSinaWeibo.authorize(mActivity, mSinaAuthListener);
		// // mSinaWeibo.authorize(mActivity, listener);
		// return;
		// }

		mActivity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				MyToastUtil.getInstance().showToastOnCenter(
						mActivity.getString(R.string.TxtStartSharing));
				if (mCallback != null) {
					mCallback.onStartShare();
				}
			}
		});

		new Thread() {
			@Override
			public void run() {
				if (misAddLoovee) {
					try {
						mSinaWeibo.createFriendship(
								ALNumericUtils.parseLong(SnsConfig.SINA_LOOVEE_OFFICAL_UID, 0),
								new RequestListener() {

									@Override
									public void onIOException(IOException arg0) {
										// TODO Auto-generated method stub
										arg0.printStackTrace();
										if (mCallback != null)
											mCallback
													.onFailed(IWeiboShare.ACTION_FOLLOW);

									}

									@Override
									public void onError(WeiboException arg0) {
										// TODO Auto-generated method stub
										arg0.printStackTrace();
										// 20506：已关注，忽略此错误
//										if (arg0.getStatusCode() != 20506) {
//											if (mCallback != null)
//												mCallback
//														.onFailed(IWeiboShare.ACTION_FOLLOW);
//										}
										
										if (mCallback != null)
											mCallback
													.onFailed(IWeiboShare.ACTION_FOLLOW);
										
									}

									@Override
									public void onComplete(String arg0) {
										// TODO Auto-generated method stub
										ALLog.e("成功了  " + arg0);
										if (mCallback != null)
											mCallback
													.onSuccess(IWeiboShare.ACTION_FOLLOW);
									}

									@Override
									public void onComplete4binary(
											ByteArrayOutputStream arg0) {
										// TODO Auto-generated method stub
										
									}
								});
						misAddLoovee = false;
					} catch (WeiboException e) {
						e.printStackTrace();

						// // 20506：已关注，忽略此错误
						// if (e.getStatusCode() != 20506) {
						// if (mCallback != null)
						// mCallback.onFailed(IWeiboShare.ACTION_FOLLOW);
						// }
					}

					// if (mCallback != null)
					// mCallback.onSuccess(IWeiboShare.ACTION_FOLLOW);
				}

				if (mIsShare) {
					String content = mContent + " ";
					// + WeiboShareUtil.getMyHomePageUrl();
					ALLog.e("sina share : " + content);

					// Date date = new Date(System.currentTimeMillis());
					// content = content + "  " + date.toGMTString();

					boolean shareWithLocalImage = false;

					if (!mShareWithImageUrl) {
						if (!TextUtils.isEmpty(mImageFile)) {
							try {
								File file = new File(mImageFile);
								if (file.exists())
									shareWithLocalImage = true;
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}

					try {
						if (shareWithLocalImage) {
							ALLog.e("你分享了图片哦" + mImageFile);
							mSinaWeibo.updateStatusWithImage(content,
									mImageFile, listener);

						} else {
							ALLog.e("不分享图片吗？亲");
							String imageUrl;
							if (!TextUtils.isEmpty(mImageUrl)) {
								imageUrl = mImageUrl;
							} else {
//								imageUrl = WeiboShareUtil
//										.getDefaultLooveeAppLogoUrl();
							}
							imageUrl = mImageUrl;

							mSinaWeibo.updateStatusWithImageUrl(content,
									imageUrl, listener);
						}

						mIsShare = false;
					} catch (WeiboException e) {
						e.printStackTrace();

						// 20017：提交相似的信息，忽略此错误
						// 20019：提交相同的信息，忽略此错误
						// if (e.getStatusCode() != 20017
						// && e.getStatusCode() != 20019) {
						// if (mCallback != null)
						// mCallback.onFailed(IWeiboShare.ACTION_SHARE);
						// }
					}

					// if (mCallback != null)
					// mCallback.onSuccess(IWeiboShare.ACTION_SHARE);
				}

				// mIsDoingShare = false;
			}
		}.start();
	}

	private RequestListener listener = new RequestListener() {

		@Override
		public void onIOException(IOException e) {
			ALLog.e("分享失败"+e.toString());
			if (mCallback != null)
				mCallback.onFailed(IWeiboShare.ACTION_SHARE);

		}

		@Override
		public void onError(WeiboException e) {
			// 20017：提交相似的信息，忽略此错误
			// 20019：提交相同的信息，忽略此错误
			ALLog.e("分享失败"+e.toString());
//			if (e.getStatusCode() != 20017 && e.getStatusCode() != 20019) {
//				if (mCallback != null)
//					mCallback.onFailed(IWeiboShare.ACTION_SHARE);
//			}
			
			if (mCallback != null)
				mCallback.onFailed(IWeiboShare.ACTION_SHARE);
		}

		@Override
		public void onComplete(String response) {
			ALLog.e("update status ： " + response);
			if (mCallback != null)
				mCallback.onSuccess(IWeiboShare.ACTION_SHARE);

		}

		@Override
		public void onComplete4binary(ByteArrayOutputStream arg0) {
			// TODO Auto-generated method stub
			
		}
	};

	private OnAuthEventListener mSinaAuthListener = new OnAuthEventListener() {

		@Override
		public void onAuthSuccess() {
			ALLog.e(String.format("新浪微博授权验证成功, access token : %s",
					mSinaWeibo.getAccessToken().getToken()));

			mForceLogin = false;

			if (mShareFlag) {
				doShare();
			} else {

				if (mCallback != null) {
					mCallback.onSuccess(IWeiboShare.ACTION_AUTHORIZE);
				}
			}
		}

		@Override
		public void onCancel() {
			ALLog.e("取消新浪微博授权");

			// mIsDoingShare = false;
		}

		@Override
		public void onAuthFailed(String msg) {
			ALLog.e(String.format("新浪微博授权失败, msg : %s", msg));

			if (mCallback != null)
				mCallback.onFailed(IWeiboShare.ACTION_AUTHORIZE);

			// mIsDoingShare = false;
		}

	};

	private OnAuthEventListener mSinaGetFriendsAuthListener = new OnAuthEventListener() {

		@Override
		public void onAuthSuccess() {
			ALLog.e(String.format("新浪微博授权验证成功, access token : %s",
					mSinaWeibo.getAccessToken().getToken()));

			mForceLogin = false;

			if (mGetFriendsFlag) {
				// doShare();
				// mSinaWeibo.getFriends(content, imageUrl, listener);
				doGetFriends();
			} else {

				if (mCallback != null) {
					mCallback.onSuccess(IWeiboShare.ACTION_AUTHORIZE);
				}
			}
		}

		@Override
		public void onCancel() {
			ALLog.e("取消新浪微博授权");

			// mIsDoingShare = false;
		}

		@Override
		public void onAuthFailed(String msg) {
			ALLog.e(String.format("新浪微博授权失败, msg : %s", msg));

			if (mCallback != null)
				mCallback.onFailed(IWeiboShare.ACTION_AUTHORIZE);

			// mIsDoingShare = false;
		}

	};

	@Override
	public void getFriends(Activity activity, Callback callback) {
		// TODO Auto-generated method stub
		mSinaWeibo = ThirdPartFactory.getSinaWeiboInstance(activity);
		mActivity = activity;
		mCallback = callback;

		if (!mSinaWeibo.isSessionValid()) {
			mGetFriendsFlag = true;
			mSinaWeibo.authorize(mActivity, mSinaGetFriendsAuthListener);
			return;
		}
		doGetFriends();
	}

	private RequestListener getFriendslistener = new RequestListener() {

		@Override
		public void onIOException(IOException e) {
			e.printStackTrace();
			if (mCallback != null) {
				mCallback.onGetFriends(null);
			}
		}

		@Override
		public void onError(WeiboException e) {
			e.printStackTrace();
			if (mCallback != null) {
				mCallback.onGetFriends(null);
			}
		}

		@Override
		public void onComplete(String response) {
			try {
				ArrayList<User> contactcs = new ArrayList<User>();
				User u = null;
				JSONArray jsonArray = new JSONObject(response)
						.getJSONArray("users");
				for (int index = 0; index < jsonArray.length(); index++) {
					JSONObject json = (JSONObject) jsonArray.opt(index);
					Log.d("LL", json.getString("idstr"));
					u = new User();
					u.setNick(json.getString("screen_name"));
					u.setJid(json.getString("idstr"));
					// 头像
					u.setImageFileId(json.getString("profile_image_url"));
					contactcs.add(u);
				}
				if (mCallback != null) {
					mCallback.onGetFriends(contactcs);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				if (mCallback != null) {
					mCallback.onGetFriends(null);
				}
			}

		}

		@Override
		public void onComplete4binary(ByteArrayOutputStream arg0) {
			// TODO Auto-generated method stub
			
		}
	};

	private void doGetFriends() {
		mSinaWeibo.getFriends(getFriendslistener);
	}
}
